<?php

class User_IndexController extends Ac_Controller_Action
{
    /**
     *
     */
    public function init()
    {
        /* Initialize action controller here */
        if(!empty($this->loggedin_user)){
            $this->view->user= $this->loggedin_user;
        }
    }

    /**
     *
     */
    public function indexAction()
    {
        $this->addTitle('account Admin');
        if(empty($this->loggedin_user)){
            //raise an exception
            throw new Exception("Must be logged in to access User Dashboard");
        }

        $this->view->getNoPublishedAds = $this->loggedin_user->getNoPublishedAds();
        $this->view->getNoViews = $this->loggedin_user->getNoViews();
        $this->view->getNoShares = $this->loggedin_user->getNoShares();
        $this->view->getNoResponses = $this->loggedin_user->getNoResponses();
        $this->view->subAccounts = '7';
    }

    /**
     *
     */
    public function loginAction()
    {
       $this->_helper->_layout->setLayout('login-layout');
       $this->addTitle('登录');
       $form = new User_Form_LoginForm();
       $to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');

       if ($this->_request->isPost() && $form->isValid($_POST['login'])) {
           $user = new Model_User();
           $form->setUser($user);
           try {
               if($form->save()) {
               		$loggedin_user_id = Zend_Registry::get('loggedin_user')->_id;
					Model_User::update(array('_id'=>new MongoId($loggedin_user_id)), array('$set'=>array('l_t'=>new MongoDate(time()), 'emd'=>'0')));
               		
                    if(!empty($_COOKIE['ac_bookmark'])){
				       	$uid = $_COOKIE['ac_bookmark'];
					   	$obj = Model_Visit::all(array('uid'=> $uid));
					   	foreach ($obj as $val){
					   		Model_Visit::update(array('_id'=>$val->_id), array('$set'=>array('us'=>$loggedin_user_id), '$unset'=>array('uid'=>$uid)));
					   	}
					   	$obj_like = Model_Like::all(array('uid'=>$uid));
					   	foreach ($obj_like as $val){
					   		if(Model_Like::one(array('us'=>$loggedin_user_id, 'obj'=>$val->obj))){
					   			Model_Like::remove(array('_id'=>$val->_id));
					   		}else{
					   			Model_Like::update(array('_id'=>$val->_id), array('$set'=>array('us'=>$loggedin_user_id), '$unset'=>array('uid'=>$uid)));
					   		}
					   	}
		       	   	}
		       	   	
               		
               		//for biz accounts, redirect to biz info form
               		$temp = Zend_Registry::get('loggedin_user');
			   		if ($temp->type_account & Model_User::COMPANY_ADMIN) 
					{
			            $company = $temp->company;
			            if(empty($company->cn) || empty($company->bc))
			            {
			            	if(!empty($to_be_confirmed_ads->arr)){
								$this->_redirect($this->view->geturl('register-business-info', 'user', null, null, array('inc' => '2')));
							}else{
								$this->_redirect($this->view->geturl('register-business-info', 'user', null, null, array('inc' => '1')));
								//$this->_redirect($this->view->geturl('index', 'default', null, null, array('login' => '1')));
							}
							
						}
			        }
               		
                   if (!empty($to_be_confirmed_ads->arr)) {
                        $this->_redirect($this->view->geturl('post-registration-post-an-ad', 'user', null, null, array('return'=> (string) $ad->_id, 'login_process'=>1)));
                   }
                   else 
				   {
                        $session = new Zend_Session_Namespace('previous_page');
                        if (!empty($session->url)) {
                            $url = $session->url;
                            $session->unsetAll();
                            $this->_redirect($url);
                        } else {
                            $this->_redirect($this->view->geturl('my-account', 'user'));
    						//$this->_redirect($this->view->geturl('index', 'default', null, null, array('login' => '1')));
                        }
                   }
               }
               throw new Ac_User_Behavior_Exception('Credential incorrect');
           }  catch (Ac_User_Behavior_Exception $e) {
               //Exception should come from behavior class not the exception above
               $form->addError($e->getMessage());
           }
       }
       $this->view->form_login = $form;
    }

    public function registerPostAdAction()
    {
       $this->_helper->_layout->setLayout('login-layout');
       $form1 = new User_Form_LoginForm();
       $form2 = new User_Form_RegisterPersonalForm();


       $this->view->form_login = $form1;
       $this->view->form_register = $form2;
    }

    public function logoutAction()
    {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_redirect('/');
    }

    public function twitterAction()
    {
       $user = new Model_User();
       $user->setBehavior(new Ac_User_Behavior_Twitter($this->view->geturl('twitter','user')));
       $user->login();
       if (Zend_Auth::getInstance()->hasIdentity()) {
           $this->_redirect($this->view->geturl('post-registration', 'user', null, null, array('type' => 'twitter')));
       }
    }

    public function facebookAction()
    {
       $user = new Model_User();
       $user->setBehavior(new Ac_User_Behavior_Facebook($this->view->geturl('facebook','user')));
       $user->login();
       if (Zend_Auth::getInstance()->hasIdentity()) {
           $this->_redirect($this->view->geturl('post-registration', 'user', null, null, array('type' => 'facebook')));
       }
    }
    
    public function googleAction()
    {
       $user = new Model_User();
       $user->setBehavior(new Ac_User_Behavior_Google($this->view->geturl('google','user')));
       $user->login();
       if (Zend_Auth::getInstance()->hasIdentity()) {
           $this->_redirect($this->view->geturl('post-registration', 'user', null, null, array('type' => 'google')));
       }
    }

    public function registerAction()
    {
    	$this->_helper->_layout->setLayout('login-layout');
    	
    	$this->view->testi = Model_Testimonial::getSignuppage();
        $this->addTitle('注册');
    	
    	$this->render('pre-register');
    }

    public function registerCompanyAction()
    {
       $this->_helper->_layout->setLayout('login-layout');
       $this->addTitle('注册');
       $form = new User_Form_RegisterCompanyForm();
       if ($this->_request->isPost() && $_POST['personal']['type'] == 'company' && $form->isValid($_POST)) {
           $user = new Model_User();
           $form->setUser($user);
           try {
               if($form->save()) {
                   $this->_redirect($this->view->geturl('post-registration-post-an-ad', 'user', null, null, array('return'=> (string) $ad->_id)));
               }
               throw new Ac_User_Behavior_Exception('Credential incorrect');
           }  catch (Ac_User_Behavior_Exception $e) {
               //Exception should come from behavior class not the exception above
               $form->addError($e->getMessage());
           }
       }
       $this->view->form_register_company = $form;
    }

    public function validateRegisterPersonalAction()
    {
       $form = new User_Form_RegisterPersonalForm();
       unset($_POST['newaccount']['captcha']);
       $form->isValidPartial($_POST);
       $this->_helper->json($form->getMessages());
    }

    public function validateRegisterCompanyAction()
    {
       $form = new User_Form_RegisterCompanyForm();
       unset($_POST['personal']['captcha']);
       $form->isValidPartial($_POST);
       $this->_helper->json($form->getMessages());
    }

    public function confirmProfilePicAction()
    {
        $this->loggedin_user->profile_picture = $_POST['url'];
        $this->loggedin_user->save();
        $this->_helper->json(array('result' => '1'));
    }

    public function confirmCompanyPicAction()
    {
    	//echo $_POST['url']; exit();
        if ($this->loggedin_user->type_account & Model_User::COMPANY_ADMIN) {
            $company = $this->loggedin_user->company;
            $company->image = $_POST['url'];
            $company->save();
            $this->_helper->json(array('result' => '1'));
        }
        $this->_helper->json(array('result' => '0'));
    }

    public function postRegistrationAction()
    {
        if(empty($this->loggedin_user)){
            if ($this->_request->isGet() && !$this->_request->isXmlHttpRequest()) {
                $session = new Zend_Session_Namespace('previous_page');
                $session->url = $_SERVER['REQUEST_URI'];
            }
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        $to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
        $arr = (array) $to_be_confirmed_ads->arr;
        if (!empty($arr)) {
            $to_add = null;
            if (!empty($_GET['type'])) {
                $to_add[$_GET['type']] = 1;
            }
            $this->_redirect($this->view->geturl('post-registration-post-an-ad', 'user', null, null, $to_add));
            return;
        }

        if (strpos($this->loggedin_user->email, 'gmail.com')) {
            $this->view->email_url = 'http://gmail.com';
        } elseif (strpos($this->loggedin_user->email, 'hotmail.com')) {
            $this->view->email_url = 'http://hotmail.com';
        }
        if (empty($this->loggedin_user->cid)) {
            $this->render('post-registration-personal');
        } else {
            $this->render('post-registration-company');
        }
    }


    public function postRegistrationPostAnAdAction() {

        if (empty($this->loggedin_user)) {
            if ($this->_request->isGet() && !$this->_request->isXmlHttpRequest()) {
                $session = new Zend_Session_Namespace('previous_page');
                $session->url = $_SERVER['REQUEST_URI'];
            }
            $this->_redirect($this->view->geturl('login', 'user'));
        }

        $to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
        $arr = (array) $to_be_confirmed_ads->arr;

        $ads = array();
        $adid = "";
        foreach ($arr as $ad_id) {
            $ad = Model_Listing::find($ad_id);

            if (!empty($ad)) {
                /*
                //$cat = $ad->category;
                //echo "<pre>";print_r($cat[0]->_id);echo "</pre>";exit();
                if ((string) $ad->category[0]->_id == '4cda48368835c1d4132e0000') {
                    if (Zend_Registry::isRegistered('loggedin_user')) {
                        $user = Zend_Registry::get('loggedin_user');
                        if ($user->type_account == 1) {
                            $ad->category = new MongoId('4cda3e818835c16810630100');
                        } elseif ($user->type_account == 6) {
                            $ad->category = new MongoId('4cda3e818835c16810670100');
                        }
                    }
                }
                 */
                
                $ad->status = Model_Listing::STATUS_PUBLISHED;
                $ad->user = $this->loggedin_user->_id;
                $adid = $ad->_id;
                $ad->save();
                $ads[] = $ad;
            }
        }

        $to_be_confirmed_ads->unlock();
        unset($to_be_confirmed_ads->arr);

        $this->view->ads_activated = $ads;

        if (!empty($_GET['login_process'])) {
            $this->view->login_process = 1;
        }


        if (strpos($this->loggedin_user->email, 'gmail.com')) {
            $this->view->email_url = 'http://gmail.com';
        } elseif (strpos($this->loggedin_user->email, 'hotmail.com')) {
            $this->view->email_url = 'http://hotmail.com';
        }

        /*if (empty($this->loggedin_user->cid)) {
            //Sign up Process
            if (empty($arr)) {
                $this->render('post-registration-personal');
            } else {
                $this->render('post-registration-post-an-ad-personal');
            }
        } else {
            //Sign up Process
            if (empty($arr)) {
                //$this->render('post-registration-company');
                $this->_redirect($this->view->geturl('my-account', 'user', null, null, array('new' => 1)));
            } else {
                $this->render('post-registration-post-an-ad-company');
            }
        }*/
        //print_r($ads);exit();
        
        $this->_redirect($this->view->geturl('posting-success', 'listing', null, null, array('new' => (string) $adid)));
    }

    public function completeLoginAction()
    {
        $user = $this->loggedin_user;
        if (!$user->isProfileComplete()) {
            $form = new User_Form_CompleteProfileForm(array('initialize' => false));
            $form->setUser($user);
            $form->init();
            if ($this->_request->isPost() && $form->isValid($_POST)) {
                $form->save();
                $this->_redirect($this->view->geturl('my-account', 'user'));
            }
            $this->view->form = $form;
        } else {

            $this->_redirect($this->view->geturl('my-account', 'user'));
        }
    }

	public function myAccountReverseAction()
    {
		$company = $this->loggedin_user->company;
		$company->status = Model_Company::STATUS_BANNED;
		$company->save();
		$this->loggedin_user->type_account = Model_User::PERSONAL;
		unset($this->loggedin_user->cid);
		$this->loggedin_user->save();
		
		$this->_redirect($this->view->geturl('my-account', 'user'));
	}
	
	public function myAccountUpgradeAction()
    {
		if($this->loggedin_user->type & Model_User::COMPANY_ADMIN){
            $this->_redirect($this->view->geturl('my-account', 'user'));
        } 
		/* echo $this->loggedin_user->type;
		echo '<pre>';
		print_r($this->loggedin_user->company);
		echo '</pre>';
		exit;   */
		//$flag = true;
		//$this->_helper->_layout->setLayout('login-layout');
		if (empty($this->loggedin_user->cid)){
			$company = new Model_Company();
			$company->save();
			$cid = $company->_id;
			$this->loggedin_user->type_account = Model_User::COMPANY_ADMIN;
			$this->loggedin_user->cid = new MongoId($cid);
			$this->loggedin_user->save();
		}
		/*if ($this->_request->isPost()){
			
			$company = $this->loggedin_user->company;
			if (!empty($_POST['contact_firstname'])) {
                $company->contact_firstname = $_POST['contact_firstname'];
            }
            else  { unset($company->contact_firstname); }
            if (!empty($_POST['contact_lastname'])) {
                $company->contact_lastname = $_POST['contact_lastname'];
            }
            else  { unset($company->contact_lastname); }
			if (!empty($_POST['company_name'])) {
				if ($company->company_name != $_POST['company_name']) {
					$num = Model_Company::one(array('username' => $_POST['company_name']));
				} else {
					$num = NULL;
				}
				if (!empty($num)) {
					$flag = false;
					$this->view->company_name_status = 1;
				} else {
					$company->company_name = $_POST['company_name'];
					$company->username = $_POST['company_name'];
				}
				
            }
			if (!empty($_POST['contact_phone'])) {
                $company->phone = $_POST['contact_phone'];
            }
            else  { unset($company->phone); }
			if (!empty($_POST['business_category'])) {
                $company->business_category = new MongoId($_POST['business_category']);
            }
			if (!empty($_POST['phone'])) {
                $company->contact_phone = $_POST['phone'];
            }
            else  { unset($company->contact_phone); }
			if (!empty($_POST['website'])) {
                $company->website = ($_POST['website'] == 'http://' || $_POST['website'] == '') ? '' : $_POST['website'];
            }
            else  { unset($company->website); }
			if (!empty($_POST['mailing_address'])) {
                $company->mailing_address = ($_POST['mailing_address'] == 'e.g.: 8 Lucky Building, 88 Caine Road, Central' || $_POST['mailing_address'] == '') ? '' : $_POST['mailing_address'];
            }
            else  { unset($company->mailing_address); }
			if (!empty($_POST['contact_job'])) {
                $company->contact_job = $_POST['contact_job'];
            }
            else  { unset($company->contact_job); }
            if (!empty($_POST['contact_department'])) {
                $company->contact_department = $_POST['contact_department'];
            }
            else  { unset($company->contact_department); }
			if (!empty($_POST['contact_email'])) {
                $company->contact_email = $_POST['contact_email'];
            }
            else  { unset($company->contact_email); }
			if (!empty($_POST['about'])) {
                $company->about = $_POST['about'];
            }
            else  { unset($company->about); }
			 if (!empty($_POST['number_employees'])) {
                $company->number_employees = $_POST['number_employees'];
            }
            else  { unset($company->number_employees); }
            if (!empty($_POST['location'])) {
                $company->location = new MongoId($_POST['location']);
            }
            else  { unset($company->location); }
            if (!empty($_POST['fax'])) {
                $company->fax = $_POST['fax'];
            }
            else  { unset($company->fax); }
            if (!empty($_POST['facebook_twitter'])) {
                $company->facebook_twitter = ($_POST['facebook_twitter'] == 'http://' || $_POST['facebook_twitter'] == '') ? '' : $_POST['facebook_twitter'];
            }
            else  { unset($company->facebook_twitter); } 
			

			if (!empty($_FILES)) {
					
				if (($_FILES['upload1']['error'] != 4) || ($_FILES['uploadlogo']['error'] != 4)) {
					$_SERVER['NOT_JSON'] = 1;
					$res = Ac_Util::uploadCompanyPhotoProcess();
				}
				
			}
			
			//$company->username = $this->loggedin_user->username;
			if ($flag){
				$company->save();
				$this->view->update_status = 2;
				$this->_redirect($this->view->geturl('my-company-profile', 'user', null, null, array('upgradesuccess'=> 2)));
			}
		} */
		$this->_redirect($this->view->geturl('register-business-info', 'user', null, null, array('new' => 1)));
	}
	
    public function myAccountAction()
    {
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            if ($this->_request->isGet() && !$this->_request->isXmlHttpRequest()) {
                $session = new Zend_Session_Namespace('previous_page');
                $session->url = $_SERVER['REQUEST_URI'];
            }
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        
        //for biz accounts, redirect to biz info form
   		$temp = $this->loggedin_user;
   		if ($temp->type_account & Model_User::COMPANY_ADMIN) 
		{
            $company = $temp->company;
            if(empty($company->cn) || empty($company->bc))
            {
            	if(!empty($to_be_confirmed_ads->arr)){
					$this->_redirect($this->view->geturl('register-business-info', 'user', null, null, array('inc' => '2')));
				}else{
					$this->_redirect($this->view->geturl('register-business-info', 'user', null, null, array('inc' => '1')));
					//$this->_redirect($this->view->geturl('index', 'default', null, null, array('login' => '1')));
				}
				
			}
        }
		
        $this->addTitle($this->view->t('My account'));
        $this->addTitle($this->view->t('account Admin'));

        if (strpos($this->loggedin_user->email, 'gmail.com')) {
            $this->view->email_url = 'http://gmail.com';
        } elseif (strpos($this->loggedin_user->email, 'hotmail.com')) {
            $this->view->email_url = 'http://hotmail.com';
        }
		$this->view->latestAds = Model_Listing::all(array('us' => $this->loggedin_user->_id, 'sa' => Model_Listing::STATUS_PUBLISHED))->limit(10)->sort(array('p_dt' => -1));
        $this->view->getNoViews = $this->loggedin_user->getNoViews();
        $this->view->getNoShares = $this->loggedin_user->getNoShares();
        $this->view->following = Model_Follow::getFollowing($this->loggedin_user->_id);
        $user = $this->loggedin_user;
        if (!empty($user->cid)) {
            $user = $user->company;
        }
        $this->view->follower = Model_Follow::all(array('us_f' => $user->_id, 'us' => array('$exists' => true)))->limit(10);
        $this->view->liker = Model_Like::distinct('us', array('us_ob' => $this->loggedin_user->_id));
    }
	
	public function myAccountFollowerAction(){
		if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            if ($this->_request->isGet() && !$this->_request->isXmlHttpRequest()) {
                $session = new Zend_Session_Namespace('previous_page');
                $session->url = $_SERVER['REQUEST_URI'];
            }
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        
        $per_page = 9;
        $page = !empty($_GET['page']) ? $_GET['page'] : 1;
        $this->view->listing_number = 0;
        
        $user = $this->loggedin_user;
        if (!empty($user->cid)) {
            $user = $user->company;
        }
        
        $this->view->list = Model_Follow::all(array('us_f' => $user->_id, 'us' => array('$exists' => true)))->limit($per_page)->skip(($page-1)*$per_page);
        $this->view->has_uid = Model_Follow::all(array('us_f' => $user->_id, 'uid' => array('$exists' => true)))->count();
        $this->view->listing_number = Model_Follow::all(array('user_followed' => $user->_id, 'us' => array('$exists' => true)))->count();
        $this->view->page           = $page;
        $this->view->per_page       = $per_page;
	}
	
	public function myAccountFollowingAction(){
		if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            if ($this->_request->isGet() && !$this->_request->isXmlHttpRequest()) {
                $session = new Zend_Session_Namespace('previous_page');
                $session->url = $_SERVER['REQUEST_URI'];
            }
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        
        $per_page = 9;
        $page = !empty($_GET['page']) ? $_GET['page'] : 1;
        $this->view->listing_number = 0;
        
        $user = $this->loggedin_user;
        if (!empty($user->cid)) {
            $user = $user->company;
        }
        
        $this->view->list = Model_Follow::all(array('us' => $user->_id))->limit($per_page)->skip(($page-1)*$per_page);
        $this->view->listing_number = Model_Follow::all(array('user' => $user->_id))->count();
        $this->view->page           = $page;
        $this->view->per_page       = $per_page;
	}
	
	public function myAccountLikeAction(){
		if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            if ($this->_request->isGet() && !$this->_request->isXmlHttpRequest()) {
                $session = new Zend_Session_Namespace('previous_page');
                $session->url = $_SERVER['REQUEST_URI'];
            }
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        
        $per_page = 9;
        $page = !empty($_GET['page']) ? $_GET['page'] : 1;
        $this->view->listing_number = 0;
        
        $user = $this->loggedin_user;
        if (!empty($user->cid)) {
            //$user = $user->company;
        }
        
        $this->view->list = Model_Like::all(array('us_ob' => $user->_id, 'us' => array('$exists' => true)))->limit($per_page)->skip(($page-1)*$per_page);
        $this->view->has_uid = Model_Like::all(array('us_ob' => $user->_id, 'uid' => array('$exists' => true)))->count();
        $this->view->listing_number = Model_Like::all(array('us_ob' => $user->_id, 'us' => array('$exists' => true)))->count();
        $this->view->page           = $page;
        $this->view->per_page       = $per_page;
	}
	
    public function forgetPasswordAction()
    {
        $this->_helper->_layout->setLayout('forget-password-layout');
        $form = new User_Form_ForgetPasswordForm();
        if ($this->_request->isPost() && $form->isValid($_POST)) {
            $form->save();
            $this->view->email = $_POST['email'];
            $this->view->success = true;
        }
        $this->view->form = $form;
        $this->render('forget-password');
    }

    public function validateForgetPasswordAction()
    {
        $form = new User_Form_ForgetPasswordForm();
        $form->isValidPartial($_POST);
        $this->_helper->json($form->getMessages());
    }

    public function myAccountAdsAction()
    {
        if ($this->_request->isPost()) {
            //echo "<PRE>"; print_r($_POST);exit;
            //define which action has been selected
            if (!empty($_POST['action1']) || !empty($_POST['action2'])) {
                if (!empty($_POST['action1'])) {
                    $action = $_POST['action1'];
                } elseif (!empty($_POST['action2'])) {
                    $action = $_POST['action2'];
                }

                foreach($_POST['chk'] as $id) {
                    $ad = Model_Listing::find($id);
                    if($action == 'renew') {
                        $ad->renew();
                    } elseif($action == 'publish') {
                        $ad->publish();
                    } elseif($action == 'unpublish') {
                        $ad->unpublish();
                    } elseif($action == 'markassold') {
                        $ad->markAsSold();
                    } elseif($action == 'markasunsold') {
                        $ad->markAsUnSold();
                    } elseif($action == 'delete') {
                        $ad->deleteListing();
                    }
                }
            }
        }

        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect($this->view->geturl('login', 'user'));
        }

        $sort      = !empty($_REQUEST['sort']) ? $_REQUEST['sort'] : 'recent';
        $page      = !empty($_REQUEST['page']) ? $_REQUEST['page'] : 1;
        $per_page  = 10;
        $solr = Ac_Search::getClient();
        $desc = '';
        $tit = '';
        if (!empty($_REQUEST['search_text'])) {
        	$keys = explode(' ', $_REQUEST['search_text']);
        	$i=1;
        	$or = 'OR ';
        	foreach($keys as $key){
        		if($i==count($keys)){
					$or = '';
				}
				$desc .= 'description:'.$key.' '.$or;
				$tit .= 'title:'.$key.' '.$or;
				$i++;
			}
        	
            if($_REQUEST['search_type'] == 1){
                //$query = 'description:'.$_REQUEST['search_text'].' title:'.$_REQUEST['search_text'];
                $query = $desc.' '.$tit;
            } else {
                //$query = 'title:'.$_REQUEST['search_text'];
                $query = $tit;
            }
        }
        elseif (!empty($_REQUEST['search_text2'])) {
            if($_REQUEST['search_type2'] == 1){
                $query = 'description:'.$_REQUEST['search_text2'].' title:'.$_REQUEST['search_text2'];
            } else {
                $query = 'title:'.$_REQUEST['search_text2'];
            }
        }
        else {
            $query = '*:*';
        }

        $start = ($page-1) * $per_page;

        $additionalParameters['fq'] = ' +user_id:'. (string) $this->loggedin_user->_id;
        if (!empty($_REQUEST['category'])) {
            $additionalParameters['fq'] .= ' +category:'.$_REQUEST['category'];
        }
        if (!empty($_REQUEST['location']) && $_REQUEST['location'] != '_empty_') {
            $additionalParameters['fq'] .= ' +area_l2:'.$_REQUEST['location'];
        }

        $date_filter = array(
            1 => $this->view->t('最后24小时'),
            2 => $this->view->t('最后7天'),
            3 => $this->view->t('最后14天'),
            4 => $this->view->t('最后30天'),
            5 => $this->view->t('最后60天'),
            6 => $this->view->t('最后90天'),
            7 => $this->view->t('最后180天'),
        );
        
        $sort_by = array(
            'low' 	 => $this->view->t('价格↓'),
            'high' 	 => $this->view->t('价格↑'),
            'rel' 	 => $this->view->t('相关'),
            'old' 	 => $this->view->t('最新'),
            'recent' => $this->view->t('最旧'),
        );

        if (!empty($_REQUEST['post_date'])) {
            if ($_REQUEST['post_date'] == 1) {
                $date_st  = time()- 24*3600;
                $date_end  = time();
            } elseif ($_REQUEST['post_date'] == 2) {
                $date_st  = time()- 7*24*3600;
                $date_end  = time();
            } elseif ($_REQUEST['post_date'] == 3) {
                $date_st  = time()- 14*24*3600;
                $date_end  = time();
            } elseif ($_REQUEST['post_date'] == 4) {
                $date_st  = time()- 30*24*3600;
                $date_end  = time();
            } elseif ($_REQUEST['post_date'] == 5) {
                $date_st  = time()- 60*24*3600;
                $date_end  = time();
            } elseif ($_REQUEST['post_date'] == 6) {
                $date_st  = time()- 90*24*3600;
                $date_end  = time();
            } elseif ($_REQUEST['post_date'] == 7) {
                $date_st  = time()- 180*24*3600;
                $date_end  = time();
            }
            if ($_REQUEST['post_date'] == 1) {
                $start_dt = date('Y-m-d\TH:i:s\Z', $date_st);
                $end   = date('Y-m-d\TH:i:s\Z', $date_end);
            } else {
                $start_dt = date('Y-m-d\T00:00:00\Z', $date_st);
                $end   = date('Y-m-d\T23:59:59\Z', $date_end);
            }
            $additionalParameters['fq'] .= ' +posted_at:['.$start_dt.' TO '.$end.']';
        }
        
		$sort = '';        
        if (!empty($_REQUEST['sort'])) {
            $sort = $_REQUEST['sort'];
        }
        $original_sort = $sort;
        
		
        switch ($sort) {
            case 'high':
                $sort = 'price_sort desc';
                $_REQUEST['sort'] = 'high';
                break;
            case 'views':
                $sort = 'views desc';
                $_REQUEST['sort'] = 'views';

                break;
            case 'low':
                //$sort = 'is_free asc, price asc';
                $sort = 'price_sort asc';
                $_REQUEST['sort'] = 'low';
                break;
            case 'rel':
                $sort = 'score desc';
                $_REQUEST['sort'] = 'rel';
                break;
            case 'title':
                $sort = 'title_sort asc';
                $_REQUEST['sort'] = 'title';
                break;
            case 'old':
                $sort = 'posted_at asc';
                $_REQUEST['sort'] = 'old';
                break;
            default:
            case 'recent':
                $sort = 'posted_at desc';
                $_REQUEST['sort'] = 'recent';
                break;
        }
        $additionalParameters['sort'] = $sort;

        if(empty($_REQUEST['tab']) || $_REQUEST['tab'] == Model_Listing::STATUS_PUBLISHED) {
            $this->view->tab = Model_Listing::STATUS_PUBLISHED;
            $additionalParameters['fq'] .= ' +status:'.Model_Listing::STATUS_PUBLISHED;
        } else {
            $this->view->tab = Model_Listing::STATUS_DRAFT;
            $additionalParameters['fq'] .= ' +status:'.Model_Listing::STATUS_DRAFT;
        }

        
        $list = $solr->search($query, $start, $per_page, $additionalParameters);



        // filter lists
        $additionalParameters = array(
            'facet'          => 'true',
            'facet.mincount' => '1',
            'facet.field'    => array('category_attached', 'area_l2'),
            'fq'             =>'+user_id:'. (string) $this->loggedin_user->_id);

        if(empty($_REQUEST['tab']) || $_REQUEST['tab'] == Model_Listing::STATUS_PUBLISHED) {
            $additionalParameters['fq'] .= ' +status:'.Model_Listing::STATUS_PUBLISHED;
        } else {
            $additionalParameters['fq'] .= ' +status:'.Model_Listing::STATUS_DRAFT;
        }

        $list_facet = $solr->search('*:*', $start, $per_page, $additionalParameters);

//        echo '<pre style="clear:both">';
//        print_r($_REQUEST);
//        print_r($additionalParameters);
//        print_r($list_facet->facet_counts->facet_fields);
//        echo '</pre>';

        // tab count
        $additionalParameters = array(
            'facet'          => 'true',
            'facet.field'    => array('status'),
            'facet.mincount' => '1',
            'facet.query'    => array('status:[* TO 1]', 'status:[2 TO 3]'),
            'fq'             =>'+user_id:'. (string) $this->loggedin_user->_id);

        $list_tab = $solr->search('*:*', $start, $per_page, $additionalParameters);
		if (DISPLAY_DEBUG) {
            echo "<PRE style='clear:both'>"; print_r($_REQUEST);echo "<br />";print_r($additionalParameters);echo "<br />";print_r($query);echo "</PRE>";
        }

        $tabs = array(
            Model_Listing::STATUS_PUBLISHED => $list_tab->facet_counts->facet_queries->{'status:[* TO 1]'},
            Model_Listing::STATUS_DRAFT => $list_tab->facet_counts->facet_queries->{'status:[2 TO 3]'},
        );

        $this->view->list_filter    = $list_facet->facet_counts->facet_fields;
        $this->view->list_filter_date = $date_filter;
        $this->view->tabs           = $tabs;
        $this->view->list           = $list->response->docs;
        $this->view->listing_number = $list->response->numFound;
        $this->view->page           = $page;
        $this->view->per_page       = $per_page;
        $this->view->sort_by        = $sort_by;//Model_Listing::getSearchResultSort();
        $this->view->sort			= empty($original_sort) ? 'recent' : $original_sort;
        $this->addTitle('Ads');
    }
    public function showMySubaccountsAction(){
        $this->addTitle('My sub accounts');
    }

    public function myAccountProfileAction(){
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect($this->view->geturl('login', 'user'));
        }
		//$this->_helper->_layout->setLayout('layout-myaccount');
        $this->addTitle('My profile');
        if($this->_request->isPost()) {
        	$post = $_POST;
            if(isset($post['profile_btn'])){
				$arr_errors = array();
			}
            /*if (!empty($_POST['name'])) {
            	print_r($_POST);exit();
                $this->loggedin_user->nm = $_POST['name'];
            }
            else {
                if (isset($_POST['name'])) {
                    $this->loggedin_user->nm = '';
                }
            }
            if (!empty($_POST['username'])) {
                //Checking if Username Already exists
                $user = Model_User::one(array('username' => $_POST['username']));
                if (empty($user)) {
                    $this->loggedin_user->username = $_POST['username'];
                    $this->loggedin_user->save();
                    echo 'ok';exit;
                }
                else {
                    if ($this->loggedin_user->username == $_POST['username']) {
                        echo 'ok';exit;
                    }
                    else { 
						echo 'nok';exit; 
					}
                }
            }

			
			$company = $this->loggedin_user->company;
			 if (!empty($_POST['contact_firstname'])) {
                $company->contact_firstname = $_POST['contact_firstname'];
            }
            else  { unset($company->contact_firstname); }
            if (!empty($_POST['contact_lastname'])) {
                $company->contact_lastname = $_POST['contact_lastname'];
            }
            else  { unset($company->contact_lastname); }
			if (!empty($_POST['company_name'])) {
                $company->company_name = $_POST['company_name'];
            }
			if (!empty($_POST['contact_phone'])) {
                $company->contact_phone = $_POST['contact_phone'];
            }
            else  { unset($company->contact_phone); }
			if (!empty($_POST['business_category'])) {
                $company->business_category = new MongoId($_POST['business_category']);
            }
			if (!empty($_POST['phone'])) {
                $company->phone = $_POST['phone'];
            }
            else  { unset($company->phone); }
			if (!empty($_POST['website'])) {
                $company->website = $_POST['website'];
            }
            else  { unset($company->website); }
			if (!empty($_POST['mailing_address'])) {
                $company->mailing_address = $_POST['mailing_address'];
            }
            else  { unset($company->mailing_address); }
			if (!empty($_POST['contact_job'])) {
                $company->contact_job = $_POST['contact_job'];
            }
            else  { unset($company->contact_job); }
            if (!empty($_POST['contact_department'])) {
                $company->contact_department = $_POST['contact_department'];
            }
            else  { unset($company->contact_department); }
			if (!empty($_POST['contact_email'])) {
                $company->contact_email = $_POST['contact_email'];
            }
            else  { unset($company->contact_email); }
			if (!empty($_POST['about'])) {
                $company->about = $_POST['about'];
            }
            else  { unset($company->about); }
			 if (!empty($_POST['number_employees'])) {
                $company->number_employees = $_POST['number_employees'];
            }
            else  { unset($company->number_employees); }
            if (!empty($_POST['location'])) {
                $company->location = new MongoId($_POST['location']);
            }
            else  { unset($company->location); }
            if (!empty($_POST['fax'])) {
                $company->fax = $_POST['fax'];
            }
            else  { unset($company->fax); }
            if (!empty($_POST['facebook_twitter'])) {
                $company->facebook_twitter = $_POST['facebook_twitter'];
            }
            else  { unset($company->facebook_twitter); }
			
			$company->save();
            $this->loggedin_user->save();
            echo 'ok';exit;*/
        }

        /*if (!empty($this->loggedin_user->cid)) {
            $this->render('my-account-company-profile-holder');
        } else {*/
            $this->render('my-account-profile');
        //}

    }
	
	public function myCompanyProfileAction(){
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect($this->view->geturl('login', 'user'));
        }
		//$this->_helper->_layout->setLayout('layout-myaccount');
        $this->addTitle('My Business Profile');
        if($this->_request->isPost()) {
            if (!empty($_POST['firstname'])) {
                $this->loggedin_user->firstname = $_POST['firstname'];
            }
            else {
                if (isset($_POST['firstname'])) {
                    $this->loggedin_user->firstname = '';
                }
            }
            if (!empty($_POST['lastname'])) {
                $this->loggedin_user->lastname = $_POST['lastname'];
            }
            else {
                if (isset($_POST['lastname'])) {
                    $this->loggedin_user->lastname = '';
                }
            }
            if (!empty($_POST['username'])) {
                //Checking if Username Already exists
                $user = Model_User::one(array('username' => $_POST['username']));
                if (empty($user)) {
                    $this->loggedin_user->username = $_POST['username'];
                 //   echo 'ok';exit;
                }
                else {
                    if ($this->loggedin_user->username == $_POST['username']) {
                      //  echo 'ok';exit;
                    }
                    else { //echo 'nok';exit; 
					}
                }
            }

			$flag = true;
			$company = $this->loggedin_user->company;
			 if (!empty($_POST['contact_firstname'])) {
                $company->contact_firstname = $_POST['contact_firstname'];
            }
            else  { unset($company->contact_firstname); }
            if (!empty($_POST['contact_lastname'])) {
                $company->contact_lastname = $_POST['contact_lastname'];
            }
            else  { unset($company->contact_lastname); }
			if (!empty($_POST['company_name'])) {
				if ($company->company_name != $_POST['company_name']) {
					$num = Model_Company::one(array('username' => $_POST['company_name']));
				} else {
					$num = NULL;
				}
				if (!empty($num)) {
					$this->view->company_status = 0;	
					$flag = false;
				} else {
					$company->company_name = $_POST['company_name'];
					$company->username = $_POST['company_name'];
				}
            }
			if (!empty($_POST['contact_phone'])) {
                $company->phone = $_POST['contact_phone'];
            }
            else  { unset($company->phone); }
			if (!empty($_POST['business_category'])) {
                $company->business_category = new MongoId($_POST['business_category']);
            }
			if (!empty($_POST['phone'])) {
                $company->contact_phone = $_POST['phone'];
            }
            else  { unset($company->contact_phone); }
			if (!empty($_POST['website'])) {
                $company->website = ($_POST['website'] == 'http://' || $_POST['website'] == '') ? '' : $_POST['website'];
            }
            else  { unset($company->website); }
			if (!empty($_POST['mailing_address'])) {
                $company->mailing_address = ($_POST['mailing_address'] == 'e.g.: 8 Lucky Building, 88 Caine Road, Central' || $_POST['mailing_address'] == '') ? '' : $_POST['mailing_address'];
            }
            else  { unset($company->mailing_address); }
			if (!empty($_POST['contact_job'])) {
                $company->contact_job = $_POST['contact_job'];
            }
            else  { unset($company->contact_job); }
            if (!empty($_POST['contact_department'])) {
                $company->contact_department = $_POST['contact_department'];
            }
            else  { unset($company->contact_department); }
			if (!empty($_POST['contact_email'])) {
                $company->contact_email = $_POST['contact_email'];
            }
            else  { unset($company->contact_email); }
			if (!empty($_POST['about'])) {
                $company->about = $_POST['about'];
            }
            else  { unset($company->about); }
			 if (!empty($_POST['number_employees'])) {
                $company->number_employees = $_POST['number_employees'];
            }
            else  { unset($company->number_employees); }
            if (!empty($_POST['location'])) {
                $company->location = new MongoId($_POST['location']);
            }
            else  { unset($company->location); }
            if (!empty($_POST['fax'])) {
                $company->fax = $_POST['fax'];
            }
            else  { unset($company->fax); }
            if (!empty($_POST['facebook_twitter'])) {
                $company->facebook_twitter = ($_POST['facebook_twitter'] == 'http://' || $_POST['facebook_twitter'] == '') ? '' : $_POST['facebook_twitter'];
            }
            else  { unset($company->facebook_twitter); }
			
			if (!empty($_FILES)) {
				if (!empty($_FILES['uploadlogo'])) {
					if (($_FILES['uploadlogo']['error'] != 4)) {
						$res = Ac_Util::uploadProfilePhoto();
						$company->image = $res;
						//echo "<pre>";echo $res['uploadlogo'];echo "</pre>";exit();
					}
				}
			
				// if (($_FILES['upload1']['error'] != 4)) {
					// $_SERVER['HTTP_ADID'] = $u;
					// $_SERVER['NOT_JSON'] = 1;
					// $res = Ac_Util::uploadCompanyPhotoProcess();
				// }
				
				if (!empty($_FILES['uploadlogo'])) {
					if (($_FILES['uploadlogo']['error'] != 4)) {
					   $_SERVER['NOT_JSON'] = 1;
						$res = Ac_Util::uploadProfilePhoto();
						$company->image = (is_array($res)) ? $res['uploadlogo'] : $res;
					}
				}
			
				if (!empty($_FILES['upload1'])){
					if (($_FILES['upload1']['error'] != 4)) {
						$_SERVER['NOT_JSON'] = 1;
						$res = Ac_Util::uploadCompanyPhotoProcess();
						if (!empty($_FILES['uploadlogo'])) {
							$temp = array();
							$i = 0;
							foreach($company->photos as $photo){
								if($i == 0){
									$i = 1;
									continue;
								}
								$temp[] = $photo;
							}
							$company->photos = array_values($temp);
						}
					}
				}
			}
			

			if ($flag == true){
				$company->save();//print_r($company);exit;
				$this->loggedin_user->save();
				$this->view->update_status = 1;
			}

        }

        $this->render('my-account-company-profile');
		//$this->_redirect($this->view->geturl('my-company-profile', 'user'));

    }
	
	public function accountHolderNameAction(){
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        $this->addTitle('My profile');
        if($this->_request->isPost()) {
			if (!empty($_POST['name'])) {
                $this->loggedin_user->name = $_POST['name'];
            }
            else {
                if (isset($_POST['name'])) {
                    $this->loggedin_user->name = '';
                }
            }
            if (!empty($_POST['username'])) {
                //Checking if Username Already exists
                $user = Model_User::one(array('username' => $_POST['username']));
                if (empty($user)) {
                    $this->loggedin_user->username = $_POST['username'];
                    $this->loggedin_user->save();
                    echo '1';exit;
                }
                else {
                    if (strtolower(trim($this->loggedin_user->username)) == strtolower(trim($_POST['username']))) {   
                    	$this->loggedin_user->save();
						echo '1';exit;
                    }
                    else { 
						echo 'nok';exit; 
					}
                }
            }
            
    	}
	}
    public function accountHolderPhoneAction(){
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        $this->addTitle('My profile');
        if($this->_request->isPost()) {
            if (!empty($_POST['phone'])) {
                $this->loggedin_user->phone = $_POST['phone'];
            }
            else  { unset($this->loggedin_user->phone); }

            $this->loggedin_user->save();
            echo 'ok';exit;
        }
    }

    public function accountHolderLicenseAction(){
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        $this->addTitle('My profile');
        if($this->_request->isPost()) {
            if (!empty($_POST['license'])) {
                $this->loggedin_user->license_id = $_POST['license'];
            }
            else  { unset($this->loggedin_user->license_id); }

            $this->loggedin_user->save();
            echo 'ok';exit;
        }
    }
    
    public function accountHolderAgentNumAction(){
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        $this->addTitle('My profile');
        if($this->_request->isPost()) {
            if (!empty($_POST['agent_num'])) {
                $this->loggedin_user->agent_num = $_POST['agent_num'];
            }
            else  { unset($this->loggedin_user->agent_num); }
            
            if (!empty($_POST['services'])) {
                $this->loggedin_user->services = $_POST['services'];
            }
            else  { unset($this->loggedin_user->services); }
            
            if (!empty($_POST['contact_name'])) {
                $this->loggedin_user->contact_name = $_POST['contact_name'];
            }
            else  { unset($this->loggedin_user->contact_name); }

			if (!empty($_POST['contact_tel'])) {
                $this->loggedin_user->contact_tel = $_POST['contact_tel'];
            }
            else  { unset($this->loggedin_user->contact_tel); }
            
            if (!empty($_POST['contact_msn'])) {
                $this->loggedin_user->contact_msn = $_POST['contact_msn'];
            }
            else  { unset($this->loggedin_user->contact_msn); }

            $this->loggedin_user->save();
            echo 'ok';exit;
        }
    }

    public function accountHolderServicesAction(){
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        $this->addTitle('My profile');
        if($this->_request->isPost()) {
            if (!empty($_POST['services'])) {
                $this->loggedin_user->services = $_POST['services'];
            }
            else  { unset($this->loggedin_user->services); }

            $this->loggedin_user->save();
            echo 'ok';exit;
        }
    }
    
    public function accountHolderContactNameAction(){
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        $this->addTitle('My profile');
        if($this->_request->isPost()) {
            if (!empty($_POST['contact_name'])) {
                $this->loggedin_user->contact_name = $_POST['contact_name'];
            }
            else  { unset($this->loggedin_user->contact_name); }

            $this->loggedin_user->save();
            echo 'ok';exit;
        }
    }
    
    public function accountHolderContactTelAction(){
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        $this->addTitle('My profile');
        if($this->_request->isPost()) {
            if (!empty($_POST['agent_num'])) {
                $this->loggedin_user->license_id = $_POST['agent_num'];
            }
            else  { unset($this->loggedin_user->agent_num); }
            
            if (!empty($_POST['services'])) {
                $this->loggedin_user->services = $_POST['services'];
            }
            else  { unset($this->loggedin_user->services); }
            
            if (!empty($_POST['contact_name'])) {
                $this->loggedin_user->contact_name = $_POST['contact_name'];
            }
            else  { unset($this->loggedin_user->contact_name); }

			if (!empty($_POST['contact_tel'])) {
                $this->loggedin_user->contact_tel = $_POST['contact_tel'];
            }
            else  { unset($this->loggedin_user->contact_tel); }
            
            if (!empty($_POST['contact_msn'])) {
                $this->loggedin_user->contact_msn = $_POST['contact_msn'];
            }
            else  { unset($this->loggedin_user->contact_msn); }

            $this->loggedin_user->save();
            echo 'ok';exit;
        }
    }
    
    public function accountHolderContactMsnAction(){
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        $this->addTitle('My profile');
        if($this->_request->isPost()) {
            if (!empty($_POST['contact_msn'])) {
                $this->loggedin_user->contact_msn = $_POST['contact_msn'];
            }
            else  { unset($this->loggedin_user->contact_msn); }

            $this->loggedin_user->save();
            echo 'ok';exit;
        }
    }

    public function myAccountAccountAction(){
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        $this->addTitle('My account');
        if(!empty($_POST)) {
            //Change the password
            if ((!empty($_POST['old_password'])) && (!empty($_POST['password'])) && (!empty($_POST['password_conf']))) {
                //Check the old password
                if ($this->loggedin_user->password != Model_User::generatePassword($_POST['old_password'])) {
                    //$this->loggedin_user->password = Model_User::generatePassword($_POST['password']);
                    //$this->loggedin_user->save();
                    //print_r($this->loggedin_user->password.' '.Model_User::generatePassword($_POST['old_password']));exit;
                    $res = 'nok';
                    $this->_helper->json(array('res' => $res));
                } else {
                    $this->loggedin_user->password = Model_User::generatePassword($_POST['password']);
                    $this->loggedin_user->save();
                    $res = 'ok';
                }
            }
			

            //Change the language
            if (!empty($_POST['profile_language'])) {
                $this->loggedin_user->language = $_POST['profile_language'];
                $this->loggedin_user->save();
                $res = 'ok';
            }
            $res = 'ok';
            $this->_helper->json(array('res' => $res));
        }
    }
	
	public function accountHolderPasswordAction(){
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        $this->addTitle('My profile');
        if($this->_request->isPost()) {
            //Change the password
            if ((!empty($_POST['old_password'])) && (!empty($_POST['password'])) && (!empty($_POST['password_conf']))) {
                //Check the old password
                if ($this->loggedin_user->password != Model_User::generatePassword($_POST['old_password'])) {
                    //$this->loggedin_user->password = Model_User::generatePassword($_POST['password']);
                    //$this->loggedin_user->save();
                    //print_r($this->loggedin_user->password.' '.Model_User::generatePassword($_POST['old_password']));exit;
                    $res = 'nok';
                    $this->_helper->json(array('res' => $res));
                } else {
                    $this->loggedin_user->password = Model_User::generatePassword($_POST['password']);
                    $this->loggedin_user->save();
                    $res = 'ok';
                    $this->_helper->json(array('res' => $res));
                }
            }
            
            //Change the notification for Newsletters
            if (!empty($_POST['notif_newsletter'])) {
                $this->loggedin_user->newsletter = '1';
                $this->loggedin_user->save();
            }
            else {
                $this->loggedin_user->newsletter = '0';
                $this->loggedin_user->save();
            }
            
            exit();
        }
    }
	
    public function newsletterAction(){
        if(empty($this->loggedin_user)){
            //raise an exception
            //throw new Exception("Must be logged in to access User Dashboard");
            $this->_redirect($this->view->geturl('login', 'user'));
        }
        $this->addTitle('My account');
        if($this->_request->isPost()) {
            //Change the notification for Newsletters
            if (!empty($_POST['notif_newsletter'])) {
                $this->loggedin_user->newsletter = '1';
                $this->loggedin_user->save();
                echo $_POST['notif_newsletter'];exit;
            }
            else {
                $this->loggedin_user->newsletter = '0';
                $this->loggedin_user->save();
            }
            
            echo 'ok';exit;
        }
    }

    public function validEmailAction(){
        //if($this->_request->isGet()) {
            if (preg_match("#.[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}.#", $_REQUEST['email'])) {
                $this->_helper->json(array('res' => 'ok'));
                exit;
            }
        //}
        $this->_helper->json(array('res' => 'nok'));
        exit;
    }

    public function newsletterSubscribeAction(){
        //If the user is logged
        if($this->_request->isPost()) {
            $user = Model_User::one(array('email' => $_POST['email']));
            $exist = false;
            //If User is logged in
            if(!empty($this->loggedin_user)){
                //User already loggedin
                $user = $this->loggedin_user;
            }
            //If user is not logged in but the email already exists
            elseif (!empty($user))
            {
                $exist = true;
            }
            //If user is not logged in and the email does not exist
            else {
                //New user
                $user = new Model_User();
                $user->email = $_POST['email'];
                $user->username = Model_User::generateUsername($_POST['email']);
                $user->password = Model_User::generatePassword($_POST['email']);
            }
            $user->newsletter = '1';
            $user->save();
            $session = new Zend_Session_Namespace('newsletter');
            $session->email = $user->email;
            if ($exist) { $session->exist = true; } else { $session->exist = false; }
            //Redirection to the success page for Loggedin User
            $this->_redirect($this->view->geturl('newsletter-subscribe', 'user'));
        }
        $session = new Zend_Session_Namespace('newsletter');
        $this->view->email = $session->email;
        $this->view->exist = $session->exist;
        $this->render('newsletter-subscribe-success');
    }

    public function contactInformationAction(){
        if($this->_request->isPost()) {
            if(empty($this->loggedin_user) || !$this->loggedin_user->type_account & Model_User::COMPANY_ADMIN){
                //raise an exception
                //throw new Exception("Must be logged in to access User Dashboard");
                $this->_redirect($this->view->geturl('login', 'user'));
            }
            $company = $this->loggedin_user->company;
            if (!empty($_POST['contact_firstname'])) {
                $company->contact_firstname = $_POST['contact_firstname'];
            }
            else  { unset($company->contact_firstname); }
            if (!empty($_POST['contact_lastname'])) {
                $company->contact_lastname = $_POST['contact_lastname'];
            }
            else  { unset($company->contact_lastname); }
            if (!empty($_POST['contact_job'])) {
                $company->contact_job = $_POST['contact_job'];
            }
            else  { unset($company->contact_job); }
            if (!empty($_POST['contact_department'])) {
                $company->contact_department = $_POST['contact_department'];
            }
            else  { unset($company->contact_department); }
            if (!empty($_POST['contact_phone'])) {
                $company->contact_phone = $_POST['contact_phone'];
            }
            else  { unset($company->contact_phone); }
            if (!empty($_POST['contact_email'])) {
                $company->contact_email = $_POST['contact_email'];
            }
            else  { unset($company->contact_email); }

            $company->save();
            echo 'ok';exit;
        }
    }

    public function aboutUsAction(){
        if($this->_request->isPost()) {
            if(empty($this->loggedin_user) || !$this->loggedin_user->type_account & Model_User::COMPANY_ADMIN){
                //raise an exception
                //throw new Exception("Must be logged in to access User Dashboard");
                $this->_redirect($this->view->geturl('login', 'user'));
            }
            $company = $this->loggedin_user->company;
            if (!empty($_POST['about'])) {
                $company->about = $_POST['about'];
            }
            else  { unset($company->about); }

            $company->save();
            echo 'ok';exit;
        }
    }

    public function myDraftAdsAction(){
        $this->addTitle('My draftAds');
    }
    public function addSubaccountAction(){
        $this->addTitle('addSubaccount');
    }

    /**
     * Display user public profile
     * Should choose different views based on the type of user
     */
    public function displayAction()
    {
        $user = Model_User::one(array('username' => $this->_request->getParam('username')));

        if ($user == null || $user->status == Model_User::STATUS_BANNED || $user->status == Model_User::STATUS_DELETED) {// user not found
            throw new Ac_Exception_MissingUser();
        }



        //search for listings
        $sort      = !empty($_GET['sort']) ? $_GET['sort'] : 'recent';
        $page      = !empty($_GET['page']) ? $_GET['page'] : 1;
        $per_page  = 12;
        $solr = Ac_Search::getClient();
        if (!empty($_GET['search_text'])) {
            if($_GET['search_type'] == 1){
                $query = 'description:'.$_GET['search_text'].' title:'.$_GET['search_text'];
            } else {
                $query = 'title:'.$_GET['search_text'];
            }
        }
        elseif (!empty($_GET['search_text2'])) {
            if($_GET['search_type2'] == 1){
                $query = 'description:'.$_GET['search_text2'].' title:'.$_GET['search_text2'];
            } else {
                $query = 'title:'.$_GET['search_text2'];
            }
        }
        else {
            $query = '*:*';
        }

        $start = ($page-1) * $per_page;
        $title = $user->username;

        if (!empty($_GET['page'])) {
            $title = $this->view->t('page __1__', null, $page) .' - '.$title;
        }

        if (!empty($_GET['sort'])) {
            $title = $sort .' - '.$title;
        }

        $this->addTitle($title);

        $additionalParameters['fq'] = '+status:'.Model_Listing::STATUS_PUBLISHED.' +user_id:'. (string) $user->_id;
		
		$get = $_GET;
		
		if (!empty($get['area_l2'])) {
			$additionalParameters['fq'] .= ' +area_l2:' . $get['area_l2'];
		}
		
		if (!empty($get['bedroom'])) {
			$additionalParameters['fq'] .= ' +bedroom:' . $get['bedroom'];
		}
		
		if (!empty($get['make_car'])) {
			$additionalParameters['fq'] .= ' +make:' . $get['make_car'];
		}
		
		if (!empty($get['make_motorcycle'])) {
			$additionalParameters['fq'] .= ' +make:' . $get['make_motorcycle'];
		}
		
        $sort = '';
        
        if (!empty($_REQUEST['sort'])) {
            $sort = $_REQUEST['sort'];
        }
        $original_sort = $sort;

        switch ($sort) {
            case 'high':
                $sort = 'price desc';
                $_REQUEST['sort'] = 'high';
                break;
            case 'views':
                $sort = 'views desc';
                $_REQUEST['sort'] = 'views';

                break;
            case 'low':
                $sort = 'is_free asc, price asc';
                $_REQUEST['sort'] = 'low';
                break;
            case 'rel':
                $sort = 'score desc';
                $_REQUEST['sort'] = 'rel';
                break;
            case 'title':
                $sort = 'title_sort asc';
                $_REQUEST['sort'] = 'title';
                break;
            default:
            case 'recent':
                $sort = 'posted_at desc';
                $_REQUEST['sort'] = 'recent';
                break;
        }
        $additionalParameters['sort'] = $sort;

        if (DISPLAY_DEBUG) {
            echo "<PRE style='clear:both'>"; print_r($_REQUEST);print_r($additionalParameters);echo "</PRE>";
        }

        $list = $solr->search($query, $start, $per_page, $additionalParameters);

        $this->view->user = $user;
        $this->view->list           = $list->response->docs;
        $this->view->listing_number = $list->response->numFound;
        $this->view->page           = $page;
        $this->view->per_page       = $per_page;
        $this->view->sort_by        = Model_Listing::getSearchResultSort();
        $this->view->sort           = empty($original_sort) ? 'recent' : $original_sort;

        //load bookmark
        $list = Model_Bookmark::getList();
        $bookmark = array();
        foreach($list as $bmk) {
            if(!empty($bmk->listing)) {
                $bookmark[] = (string) $bmk->listing->_id;
            }
        }
        $this->view->bookmark = $bookmark;

        if ($user->type & Model_User::AGENT) {
            //$this->view->company = $user->company;
            //$this->render('display-company');
        } else {
            //$this->render('display-personal');
        }
        $this->render('display-personal');
    }


    /**
     * Display user public profile
     * Should choose different views based on the type of user
     */
    public function displayCompanyAction()
    {
        $company = Model_Company::one(array('username' => $this->_request->getParam('company')));

        if ($company == null || $company->status != Model_Company::STATUS_ACTIVE) {// user not found
            throw new Ac_Exception_MissingUser();
        }

        $this->addTitle($company->username);

        //search for listings
        $sort      = !empty($_GET['sort']) ? $_GET['sort'] : 'recent';
        $page      = !empty($_GET['page']) ? $_GET['page'] : 1;
        $per_page  = 12;
        $solr = Ac_Search::getClient();
        if (!empty($_GET['search_text'])) {
            if($_GET['search_type'] == 1){
                $query = 'description:'.$_GET['search_text'].' title:'.$_GET['search_text'];
            } else {
                $query = 'title:'.$_GET['search_text'];
            }
        }
        elseif (!empty($_GET['search_text2'])) {
            if($_GET['search_type2'] == 1){
                $query = 'description:'.$_GET['search_text2'].' title:'.$_GET['search_text2'];
            } else {
                $query = 'title:'.$_GET['search_text2'];
            }
        }
        else {
            $query = '*:*';
        }

        $start = ($page-1) * $per_page;

        $additionalParameters['fq'] = '+status:1 +company_id:'. (string) $company->_id;

        $sort = '';
        if (!empty($_REQUEST['sort'])) {
            $sort = $_REQUEST['sort'];
        } 
        $original_sort = $sort;        

        switch ($sort) {
            case 'high':
                $sort = 'price desc';
                $_REQUEST['sort'] = 'high';
                break;
            case 'views':
                $sort = 'views desc';
                $_REQUEST['sort'] = 'views';
                break;
            case 'low':
                $sort = 'is_free asc, price asc';
                $_REQUEST['sort'] = 'low';
                break;
            case 'rel':
                $sort = 'score desc';
                $_REQUEST['sort'] = 'rel';
                break;
            case 'title':
                $sort = 'title_sort asc';
                $_REQUEST['sort'] = 'title';
                break;
            default:
            case 'recent':
                $sort = 'posted_at desc';
                $_REQUEST['sort'] = 'recent';
                break;
        }
        $additionalParameters['sort'] = $sort;
		
		$get = $_GET;
		
		if (!empty($get['area_l2'])) {
			$additionalParameters['fq'] .= ' +area_l2:' . $get['area_l2'];
		}
		
		if (!empty($get['bedroom'])) {
			$additionalParameters['fq'] .= ' +bedroom:' . $get['bedroom'];
		}
		
		if (!empty($get['make_car'])) {
			$additionalParameters['fq'] .= ' +make:' . $get['make_car'];
		}
		
		if (!empty($get['make_motorcycle'])) {
			$additionalParameters['fq'] .= ' +make:' . $get['make_motorcycle'];
		}
		
        $list = $solr->search($query, $start, $per_page, $additionalParameters);

        $this->view->company        = $company;
        $this->view->list           = $list->response->docs;
        $this->view->listing_number = $list->response->numFound;
        $this->view->page           = $page;
        $this->view->per_page       = $per_page;
        $this->view->sort_by        = Model_Listing::getSearchResultSort();
        $this->view->sort           = empty($original_sort) ? 'recent' : $original_sort;        

        //load bookmark
        $list = Model_Bookmark::getList();
        if (!empty($list)) {
            $bookmark = array();
            foreach($list as $bmk) {
                //$bookmark[] = (string) $bmk->listing->_id;
            }
            $this->view->bookmark = $bookmark;
        }

        $this->render('display-company');
    }

    public function getBookmarkAction()
    {
        $page = $_GET['page'];
        $list = Model_Bookmark::getList()->skip($page*6);

        $res = array();
        $count = 0;
        foreach ($list as $bmk) {
            $listing = $bmk->listing;
            if (empty($listing)) {
                $bmk->deleteListing();
                continue;
            }
            $count++;
            if ($count>6) {
                break;
            }

            //Define the price value
            $price = $price1 = $price2 = '';
            if (!empty($listing->sale_price) || !empty($listing->rent_price)){
                if (!empty($listing->sale_price)) {
                    $sale_price = number_format($listing->sale_price);
                    $price1 = '<dd>'.$this->view->t('HKD __1__', null, $sale_price).'<em>'.$this->view->t('(Sale)').'</em></dd>';
                }
                if (!empty($listing->rent_price)) {
                    $rent_price = number_format($listing->rent_price);
                    $price2 = '<dd>'.$this->view->t('HKD __1__', null, $rent_price).'<em>'.$this->view->t('(Rent)').'</em></dd>';
                }
                $price = $price1.' '.$price2;
            }
            elseif (!empty($listing->is_free)){
                $price = $this->view->t('Free');
            }
            elseif (!empty($listing->is_contact)){
                $price = $this->view->t('Please contact');
            }
            elseif (!empty($listing->price)){
                $price = $this->view->t('HKD __1__', null, number_format($listing->price));
            }

            $res[] = array(
                'id' => (string) $listing->_id,
                'title' => $listing->title,
                'photo' => $this->view->thumbnail()->scale($listing->featured_photo, 65, 65),
                //'price' => 'HKD '.number_format($listing->price),
                'price' => $price,
                'url' => $listing->url(),
            );
        }
        $this->_helper->json(array('list' => $res, 'count' => $list->count()));
        echo $list->count;exit;
    }

	public function clearBookmarkAction() {
        $list = Model_Bookmark::clearList();
        if ($list->count() == 0) {
            $this->_helper->json(array('res' => 'ok'));
        } else {
            $this->_helper->json(array('res' => 'nok'));
        }
    }

    public function clearHistoryAction() {
        $list = Model_History::clearList();
        if ($list->count() == 0) {
            $this->_helper->json(array('res' => 'ok'));
        } else {
            $this->_helper->json(array('res' => 'nok'));
        }
    }

    public function getHistoryAction()
    {
        $page = $_GET['page'];
        $list = Model_History::getList()->skip($page*6);

        $res = array();
        $count = 0;
        foreach($list as $bmk) {
            $listing = $bmk->listing;
            if (empty($listing)){
                $bmk->deleteListing();
                continue;
            }
            $count++;
            if ($count>6) {
                break;
            }

            //Define the price value
            $price = $price1 = $price2 = '';
            if (!empty($listing->sale_price) || !empty($listing->rent_price)){
                if (!empty($listing->sale_price)) {
                    $sale_price = number_format($listing->sale_price);
                    $price1 = '<dd>'.$this->view->t('HKD __1__', null, $sale_price).'<em>'.$this->view->t('(Sale)').'</em></dd>';
                }
                if (!empty($listing->rent_price)) {
                    $rent_price = number_format($listing->rent_price);
                    $price2 = '<dd>'.$this->view->t('HKD __1__', null, $rent_price).'<em>'.$this->view->t('(Rent)').'</em></dd>';
                }
                $price = $price1.' '.$price2;
            }
            elseif (!empty($listing->is_free)){
                $price = $this->view->t('Free');
            }
            elseif (!empty($listing->is_contact)){
                $price = $this->view->t('Please contact');
            }
            elseif (!empty($listing->price)){
                $price = $this->view->t('HKD __1__', null, number_format($listing->price));
            }


            $res[] = array(
                'id' => (string) $listing->_id,
                'title' => $listing->title,
                'photo' => $this->view->thumbnail()->scale($listing->featured_photo, 65, 65),
                //'price' => 'HKD '.number_format($listing->price),
                'price' => $price,
                'url' => $listing->url(),
            );
        }
        $this->_helper->json(array('list' => $res, 'count' => $list->count()));
    }

    public function geocodeAction()
    {
        if ($this->_request->isPost()) {
            $company = Model_Company::find($_POST['id']);

            if (empty($company->latitude)) {
                $company->latitude = $_POST['latitude'];
            }
            if (empty($company->longitude)) {
                $company->longitude = $_POST['longitude'];
            }
            $company->save();
        }
        exit;
    }

    public function verifyLoginAction()
    {
        $id = $_GET['id'];
        $u = Model_User::find($id);
        if ($u == null) {// user not found
            throw new Ac_Exception_MissingUser();
        }
        $u->verified = 1;
        $u->save();

        $this->_redirect($this->view->geturl('my-account', 'user', null, null, array('verified'=>1)));
    }
    
    /**
    * personal or business account
    */    
    public function registerPersonalAction()
    {
        $this->_helper->_layout->setLayout('login-layout');
        $this->addTitle('注册');
        $to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');

        //echo '<pre>';print_r($_SESSION);
        //print_r($to_be_confirmed_ads);exit;

        //Personal account
        $form = new User_Form_RegisterPersonalNewForm();
        if ($this->_request->isPost() && $_POST['newaccount']['type'] == 'personal' && $form->isValid($_POST)) {
           $user = new Model_User();
           $form->setUser($user);
           try {
               if($form->save()) {
                   $session = new Zend_Session_Namespace('return _url');
                   if (!empty($session->url)) {
                        $url = $session->url;
                        unset($session->url);
                        $this->_redirect($url);
                   } else {
						if (!empty($to_be_confirmed_ads->arr)){
							$this->_redirect($this->view->geturl('post-registration-post-an-ad', 'user', null, null, array('personal' => 1, 'return'=> (string) $ad->_id)));
						} else {
							$this->_redirect($this->view->geturl('my-account', 'user', null, null, array('success'=> 1)));
							//$this->_redirect($this->view->geturl('index', 'default', null, null, array('login' => 1)));
						}
                   }
               }
               throw new Ac_User_Behavior_Exception('Credential incorrect');
           }  catch (Ac_User_Behavior_Exception $e) {
               //Exception should come from behavior class not the exception above
               $form->addError($e->getMessage());
           }
       }
       $this->view->form_register_personal_new = $form;
       
    }
    
    public function registerBusinessAction()
    {
        $this->_helper->_layout->setLayout('login-layout');
        $to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');       

        //business account
        $form = new User_Form_RegisterBusinessForm();
        if ($this->_request->isPost() && $_POST['newaccount']['type'] == 'company' && $form->isValid($_POST['newaccount'])) {
           $user = new Model_User();
           $form->setUser($user);
           try {
               if($form->save()) {
                   /*$session = new Zend_Session_Namespace('return _url');
                   if (!empty($session->url)) {
                        $url = $session->url;
                        unset($session->url);
                        $this->_redirect($url);
                   } else {
                        $this->_redirect($this->view->geturl('post-registration-post-an-ad', 'user', null, null, array('personal' => 1, 'return'=> (string) $ad->_id)));
                   }*/
                   	//save pending ads in diff status
                	$temp_user = Zend_Registry::get('loggedin_user');
                   	if(!empty($to_be_confirmed_ads->arr)){
						$temp_ad = Model_Listing::find($to_be_confirmed_ads->arr[0]);
						$temp_ad->status = Model_Listing::STATUS_BIZ_FORM_INC;
						$temp_ad->user = $temp_user->_id;
						$temp_ad->save();
						//print_r($temp_ad);exit();
					}
                   	$this->_redirect($this->view->geturl('register-business-info', 'user', null, null, array('new' => 1)));
               }
               throw new Ac_User_Behavior_Exception('Credential incorrect');
           }  catch (Ac_User_Behavior_Exception $e) {
               //Exception should come from behavior class not the exception above
               $form->addError($e->getMessage());
           }
       }
       $this->view->form_register_business = $form;
       
    }
    
    public function registerBusinessInfoAction()
	{
    	if(empty($this->loggedin_user)){
            //$this->_redirect($this->view->geturl('login', 'user'));
        }
		$this->_helper->_layout->setLayout('login-layout');
        $to_be_confirmed_ads = new Zend_Session_Namespace('to_be_confirmed_ads');
        
        //print_r($to_be_confirmed_ads->arr);
        if(!empty($_GET['try'])){
			//$temp_user = Zend_Registry::get('loggedin_user');
           	$temp_ads = Model_Listing::all(array('us'=>$this->loggedin_user->_id, 'sa'=>Model_Listing::STATUS_BIZ_FORM_INC));
           	//$temp_ads = Model_Listing::find(new MongoId('4de4bbd41a184fd74615a1eb'));
           	echo "<pre>";print_r(array('us'=>$this->loggedin_user->_id, 'sa'=>Model_Listing::STATUS_BIZ_FORM_INC));print_r($temp_ads);echo "</pre>";exit();
		}
        //business info
		$form = new User_Form_RegisterBusinessInfoForm();
        $form->populate($_POST);
		if ($this->_request->isPost() && $form->isValid($_POST)) {
		   	$user = $this->loggedin_user;
		   	$form->setUser($user);
			print_r($_POST);
		   	try {
		    	if($form->save()) {
		           	$session = new Zend_Session_Namespace('return _url');
		           	if (!empty($session->listing)) {
                        $url = $session->listing;
                        unset($session->listing);
                        $this->_redirect($this->view->geturl('post-an-ad', 'listing'));
                   	}
		           	
		           	//publish those unpublished pending ads
		           	$temp_ads = Model_Listing::one(array('us'=>$this->loggedin_user->_id, 'sa'=>Model_Listing::STATUS_BIZ_FORM_INC));
		           	//echo "<pre>";var_dump($temp_ads);echo "</pre>";exit();
		           	if(!empty($temp_ads)){
						$temp_ads->status = Model_Listing::STATUS_PUBLISHED;
						$temp_ads->save();
					}	
					
		           	if (!empty($to_be_confirmed_ads->arr)) {		                
		                $this->_redirect($this->view->geturl('post-registration-post-an-ad', 'user', null, null, array('return'=> (string) $ad->_id, 'new_add' => 1)));
		                //$this->_redirect($this->view->geturl('my-account', 'user', null, null, array('new'=> 1)));
					}else{
		           		$this->_redirect($this->view->geturl('register-business-success', 'user', null, null, array('success' => 1)));
		           		//exit; 
		           	}
		           	//$this->_redirect($this->view->geturl('my-account', 'user', null, null, array('new'=> 1)));
		        
					
				}
				//$this->_redirect($this->view->geturl('index', 'user'));
		       	throw new Ac_User_Behavior_Exception('Credential incorrect');
		   }  catch (Ac_User_Behavior_Exception $e) {
		       //Exception should come from behavior class not the exception above
		       $form->addError($e->getMessage());
		   }
		}
       	$this->view->form_register_business_info = $form;
       	//$this->render('register-business-info');
		//echo "<pre>";var_dump($this->loggedin_user);echo "</pre>";exit();
	}
    
	public function registerBusinessSuccessAction()
	{
		//$this->view->list_latest_cat = Model_Category::getLatestListing();
		$this->_helper->_layout->setLayout('login-layout');
		$this->render('register-business-success');
	}
	
    public function validateRegisterPersonalNewAction()
    {
       $form = new User_Form_RegisterPersonalNewForm();
       //unset($_POST['newaccount']['captcha']);
       $form->isValidPartial($_POST);
       $this->_helper->json($form->getMessages());
    }

    public function validateRegisterBusinessAction()
    {
       $form = new User_Form_RegisterBusinessForm();
       //unset($_POST['newaccount']['captcha']);
       $form->isValidPartial($_POST);
       $this->_helper->json($form->getMessages());
    }
    
    public function validateRegisterBusinessInfoAction()
    {
       $form = new User_Form_RegisterBusinessInfoForm();
       $form->isValidPartial($_POST);
       $this->_helper->json($form->getMessages());
    }
    
    public function confirmBusinessPicAction()
    {
    	//echo $_POST['url']; exit();
        if ($this->loggedin_user->type_account & Model_User::COMPANY_ADMIN) {
            $company = $this->loggedin_user->company;
            $company->image = $_POST['url'];
            $company->save();
            $this->_helper->json(array('result' => '1'));
        }
        $this->_helper->json(array('result' => '0'));
    }
    
	public function deleteLogoAction() {
		$temp = $this->loggedin_user;
        $company = $temp->company;
        unset($company->image);
		$company->save();
        $res = 'ok';
        $this->_helper->json(array('res' => $res));
	}
	
    public function deletePhotoAction() {
        $temp = $this->loggedin_user;
        $company = $temp->company;
        $photos = $company->photos;
        unset($photos[$_POST['num']]);
        $photos = array_values($photos);
        $company->photos = $photos;
        if (!empty($company->photos_tmp)) {
            $photos = $company->photos_tmp;
            unset($photos[$_POST['num']]);
            $photos = array_values($photos);
            $company->photos_tmp = $photos;
        }
        $company->save();
        $res = 'ok';
        $this->_helper->json(array('res' => $res));
    }

    public function featurePhotoAction() {
        //$listing = Model_Listing::find($_POST['adid']);
        $temp = $this->loggedin_user;
        $company = $temp->company;
        $photos = $company->photos;
        //unset($photos[$_POST['num']]);
        $company->featured_photo_id = (int) $_POST['id'];
        $photos = array_values($photos);
        $company->photos = $photos;
        $company->save();
        $res = 'ok';
        $this->_helper->json(array('res' => $res));
    }
	public function sardsTesterAction() {
		
		$api_key = "ABQIAAAA5eiGhBx_SQ0OPYZgDHEGeRQOGxcb_JUHEI0YsNTz-4nLjoky5RSf5pz1mUX225GNJlnklehs-d2ohA";
		$lat = 26.214936;
		$long = -98.20464;
		$url = 'http://maps.google.com/maps/geo?q=' . $lat .',' . $long . '&output=json&sensor=true_or_false&key=' . $api_key;
		
		$data = @file_get_contents($url);
		
		$jsondata = json_decode($data,true);
		
		if(is_array($jsondata )&& $jsondata ['Status']['code']==200)
		{
			  $addr = $jsondata ['Placemark'][0]['address'];
		}
		
 		
		/* $id = '4d6c9319b7ca870e34060a04';
		$data = Ac_Util::NextUrl($id);
		
		
		foreach ($data as $k => $obj) {
			echo '<pre>';
			print_r($obj);
			echo '</pre>';
		}
		exit; */
		$this->view->address = $addr;
		$this->render('sards-tester');

	}

	public function locsAction(){
		$locs = Model_Location::all()->sort(array('or'=>1));
		foreach($locs as $loc){
			echo $loc->nm_sc . " - " . $loc->id . "<br />";
		}
		exit();
		
	}
}
